
/**
 * @class Kohive.app.FileCabinetController
 * @extends ExtMVC.Controller
 * Manages the File model
 */
Kohive.app.FileCabinetController = Ext.extend(
		Kohive.controllers.KohiveController, {
			name		: 'filecabinet',
			title		: Ext.ux.Translator.translate('app_file_cabinet'),

			constructor	: function() {
				Kohive.app.FileCabinetController.superclass.constructor.call(
						this, {
							viewsPackage	: Kohive.views.filecabinet
						}
				);

				this.initEvents();

				// TODO: This is a relic of old MVC, remove it once on ExtMVC 0.6 or above
				this.registerAction('index', this.index);
				this.registerAction('refresh', this.onRefresh);
			},

			/**
			 * @action index 
			 * Renders the index view
			 */
			index		: function() {
				var store = Kohive.models.File.findAll({
							url			: this.scopedUrl('file_cabinets'),
							listeners	: {
								scope			: this,
								'beforeload'	: this.fireEvent
										.createDelegate(this,
												['before-load-files']
										),
								'load'			: this.fireEvent
										.createDelegate(this, ['files-loaded'])
							}
						});

				this.indexWindow = this.renderView('index', {
							store		: store,
							closeAction	: 'hide',
							autoShow	: true,
							listeners	: {
								scope			: this,
								'destroy-file'	: this.destroy,
								'download-file'	: this.download,
								'edit-file'		: this.edit,
								'update'		: this.update
							}
						});

				store.on('load', function(store) {
							this.indexWindow.initTagsStore(store);
						}, this);

				this.indexWindow.show();

				this.fireEvent('index');
			},

			/**
			* Refreshes the the store (if defined) in the index view of the current controller
			*/
			onRefresh	: function(shortcut) {
				// Get the index view
				var v = this.indexWindow;

				// Check if the store exists, and if it does refresh it
				if (v && v.dataGrid && v.dataGrid.store) {
					if (v.editable.editing || v.uploading)
						return;
					if (shortcut && shortcut.notificationEl)
						shortcut.notificationEl.hide();

					this.fireEvent('refresh', v.dataGrid.store);

					v.dataGrid.store.load();
					v.showRefreshing();
				};
			},

			/**
			 * @action update
			 * Updates the given file with the provided arguments
			 * @param {Kohive.models.File} file The file to update
			 * @param {Object} fields An object containing keys and values to update
			 */
			update		: function(file, fields, forceRefresh) {
				this.fireEvent('before-update');

				for (var key in fields) {
					file.set(key, fields[key]);
				};

				// update the tags array - ideally we wouldn't do this here, should be in the model somehow
				file.data.tags = [];
				if (fields.tag_list) {
					Ext.each(file.get('tag_list').split(','), function(t) {
								file.data.tags.push({
											name	: t
										});
							}, this);
				};

				file.save({
							url		: this.scopedUrl(String.format(
									"file_cabinets/{0}", file.get('id')
							)),
							scope	: this,
							success	: function() {
								this.fireEvent('update', file, forceRefresh);
							}
						});
			},

			/**
			 * @action destroy 
			 * Destroys the passed file and fires a file-destroyed event
			 * @param {Kohive.models.File} file The file to destroy
			 */
			destroy		: function(file) {
				file.destroy({
							url		: this.scopedUrl(String.format(
									"file_cabinets/{0}.json", file.get('id')
							)),
							scope	: this,
							success	: function() {
								this.fireEvent('file-destroyed', file);
							}
						});
			},

			/**
			* @action download 
			* Downloads the passed file and fires a file-downloaded event
			* @param {Kohive.models.File} file The file to destroy
			*/
			download	: function(file) {
				// Get the url of the file
				var url = file.get('url');

				// Open the file in the browser
				// TODO is this the best way to do it?
				window.location.href = url;
			},

			/**
			* @action edit 
			* Downloads the passed file and fires a file-editted event
			* @param {Kohive.models.File} file The file to edit
			*/
			edit		: function(file) {
				// // Get the url of the file
				// var url = file.get('url');
				// 
				// //show loading
				// this.indexWindow.showLoading(Ext.ux.Translator.translate('app_statusbar_loading'));
				// 
				// var conn = new Ext.data.Connection();
				// conn.request({
				// url: this.scopedUrl('file_cabinets/' + file.get('id') + '/edit_in_zoho'),
				// scope: this,
				// success: function(end) {
				// this.indexWindow.showSuccess();
				//    
				// //get the response text
				// var response = end.responseText;
				//    
				// //remove unneeded shit and get the url
				// var url = response.split("<script language='javascript'>")[1].split("</script>")[0].split("window.location.href='")[1].split("';")[0];
				//    
				// // Open the file in the browser
				// // TODO is this the best way to do it?
				// window.open(url);
				// },
				// failure: function() {
				// this.indexWindow.showFailure();
				// }
				// });
			},

			/**
			 * TODO: A hacky method to prepend the /memberships/:membership_id/ segment to the front of an AJAX
			 * request url.  This really ought to be handled by the model, so factor it out of here when possible
			 * @param {String} url The url to append to the memberships scope
			 * @return {String} The fully scoped url
			 */
			scopedUrl	: function(url) {
				return String.format("/memberships/{0}/{1}", Kohive.OS
								.getCurrentHive().get('id'), url);
			},

			/**
			 * Sets up all of the events this controller emits
			 */
			initEvents	: function() {
				this.addEvents(
						/**
				 * @event refresh
				 * Fires when the index window has been refreshed
				 * @param {paramType} paramName parameter description
				 */
						'refresh',

						/**
						 * @event before-load-files
						 * Fires before the request to load (or refresh) files is sent
						 */
						'before-load-files',

						/**
						 * @event files-loaded
						 * Fired whenever files have been retrieved
						 * @param {Ext.data.Store} files A store containing files
						 */
						'files-loaded',

						/**
						 * @event show-image
						 * Fired whenever subscriber views should update the photo they are displaying
						 * @param {Kohive.models.Image} image The new image to display
						 */
						'show-image',

						/**
						 * @event file-destroyed
						 * Fired when a file has been successfully destroyed
						 * @param {Kohive.models.File} file The file that was destroyed
						 */
						'file-destroyed',

						/**
						* @event file-downloaded
						* Fired when a file has been successfully downloaded
						* @param {Kohive.models.File} file The file that was downloaded
						*/
						'file-downloaded',

						/**
						 * @event before-update
						 * Fired before an image update request is sent
						 */
						'before-update',

						/**
						 * @event update
						 * Fired when an image has been successful updated
						 * @param {Kohive.models.Image} image The image that was updated
						 */
						'update',

						/**
						 * @event before-create-album
						 * Fires before the request to create an album is sent
						 */
						'before-create-album',

						/**
						 * @event album-created
						 * Fired when a new album has been successfully created
						 * @param {Kohive.models.Album} album The newly created album
						 */
						'album-created',

						/**
						 * @event album-destroyed
						 * Fired when an album has been destroyed
						 * @param {Kohive.models.Album} album The album that was destroyed
						 */
						'album-destroyed'
				);
			}

		}
);

Kohive.OS.registerController('filecabinet', Kohive.app.FileCabinetController);